/*
 * @filename ActionLogInterceptor.java
 * @author barry
 * @version 0.0.1
 * @date 2019年12月11日
 */
package com.bnzj.core.webmvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bnzj.core.webmvc.util.WebMvcUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import com.bnzj.core.action.log.ActionLog;
import com.bnzj.core.action.log.ActionLogService;
import com.bnzj.core.rest.CurrentUserService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author barry
 * @date 2019-12-11
 */
@Slf4j
@RequiredArgsConstructor
public class ActionLogInterceptor implements HandlerInterceptor {
    
    private final CurrentUserService currentUserService;
    
    private final ActionLogService actionLogService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (handler instanceof ResourceHttpRequestHandler) {
            return true;
        }
        String ip = WebMvcUtils.getIpAddress(request);
        String url = request.getServletPath();
        String method = request.getMethod();
        try {
            String name = "";
            String[] names = name.split("-");
            ActionLog log = actionLogService.createActionLog();
            log.setAction(url);
            log.setUrl(url);
            log.setIp(ip);
            log.setMethod(method);
            log.setActionName(name);
            log.setModuleName(names[1]);
            log.setAccount(currentUserService.getAccount());
            log.setUserName(currentUserService.getUserInfo().getName());
            actionLogService.add(log);
        } catch (Exception e) {
            log.error("", e);
        }
        return true;
    }
}
